package com.qidian.zl.paper.service.impl;

import com.qidian.zl.paper.dao.FieldDAO;
import com.qidian.zl.paper.dao.PaperDAO;
import com.qidian.zl.paper.factory.DAOFactory;
import com.qidian.zl.paper.pojo.Field;
import com.qidian.zl.paper.service.FieldService;
import com.qidian.zl.paper.util.StCache;
import com.qidian.zl.paper.util.StResult;

import java.util.List;

public class FieldServiceImpl implements FieldService {
    private FieldDAO fieldDAO=new DAOFactory().getFieldDAO();
    @Override
    public Long saveOrUpdate(Field field,String[] selectorTexts) {
        Long fieldId=-1L;
        if (field.getFieldId().equals(new Long(-1))){
           fieldId=fieldDAO.save(field,selectorTexts);
        }else {
            fieldId=fieldDAO.update(field,selectorTexts);
            String fieldKey="fields_"+field.getPaperId();
            StCache.clean(fieldKey);
            String selectorKey="slectors_"+fieldId;
            StCache.clean(selectorKey);
        }
        return fieldId;
    }

    @Override
    public void delete(Long fieldId) {
        fieldDAO.delete(fieldId);
    }

    @Override
    public StResult queryByPaperId(long paperId) {
        List<Field> fields=null;
        String key="fields_"+paperId;
        if (StCache.cache(key)){
           fields=(List<Field>) StCache.get(key);
        }else {
            fields = fieldDAO.queryByPaperId(paperId);
            StCache.put(key,fields);
        }

        return StResult.ok(fields);
    }
}
